/**
 * Uint8Array 数据流转换为 HEX字符串
 * @param buffer
 * @returns {string}
 */
// export 这个逼出去,然后引用这个逼的时候要这么的
// 你比如先一步引进来： import {buffer2hex,hextoString,stringtoHex} from '这个js的路径'
// 用方法的时候 这么的 : let c = buffer2hex(message); console.log(c)

function buffer2hex(buffer) {
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
}

/**
 * 16进制数据转换为字符串 '414243'->'ABC'
 * @param hex
 * @returns {string}
 * e.g: var a = hextoString('46474849');
 * */

function hextoString(hex) {
  let arr = hex.split('')
  let out = ''
  for (let i = 0; i < arr.length / 2; i++) {
    let tmp = '0x' + arr[i * 2] + arr[i * 2 + 1]
    let charValue = String.fromCharCode(tmp)
    out += charValue
  }
  return out
}

/**
 * 字符串转Hex 'ABC'->414243
 * @param str
 * @returns {string}
 */
function stringtoHex(str) {
  let val = ''
  for (let i = 0; i < str.length; i++) {
    if (val === '') val = str.charCodeAt(i).toString(16)
    else val += str.charCodeAt(i).toString(16)
  }
  return val
}

/**
 * 8位整数转为字节组 2个字节
 * @param {[*]} value
 */
function uint8ToBytes(value) {
  var bytes = new Uint8Array(2)
  bytes[0] = (value & 0xff00) >> 8
  bytes[1] = value & 0x00ff
  return bytes
}

/**
 * 16位整数转为字节组 4个字节
 * @param {[*]} value
 */
function uint16ToBytes(value) {
  var bytes = new Uint8Array(4)
  bytes[0] = (value & 0xff000000) >> 24
  bytes[1] = (value & 0x00ff0000) >> 16
  bytes[2] = (value & 0x0000ff00) >> 8
  bytes[3] = value & 0x000000ff
  return bytes
}
/**
 * 32位整数转为字节组 4个字节
 * @param {[*]} value
 */
function uint32ToBytes(value) {
  var bytes = new Uint8Array(8)
  bytes[0] = (value & 0xff0000000000000000) >> (8 * 7)
  bytes[1] = (value & 0x0000ff000000000000) >> (8 * 6)
  bytes[2] = (value & 0x000000ff0000000000) >> (8 * 5)
  bytes[3] = (value & 0x00000000ff00000000) >> (8 * 4)
  bytes[4] = (value & 0x0000000000ff000000) >> (8 * 3)
  bytes[5] = (value & 0x000000000000ff0000) >> (8 * 2)
  bytes[6] = (value & 0x00000000000000ff00) >> 8
  bytes[7] = value & 0x0000000000000000ff
  return bytes
}

function bytesToUint(value) {
  var mask = 0xff
  var temp = 0
  var n = 0
  for (var i = 0; i < value.length; i++) {
    n <<= 8
    temp = value[i] & mask
    n |= temp
  }
  return n
}
